package com.briup.ch11;


import java.io.*;

/**
 * @Author briup-adam
 * @Date 2023/10/19 上午10:15
 * @Description
 **/

public class ByteArrayReadAndWrite {
    static void write() {
        FileInputStream fis = null;
        ByteArrayOutputStream baos = null;

        try {
            fis = new FileInputStream("02code/src/背影.txt");
            baos = new ByteArrayOutputStream();

            byte[] b = new byte[8];
            int len = 0;
            while ((len = fis.read(b)) != -1) {
                baos.write(b, 0, len);
            }
            baos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
//将字节数组输出流的内部数组 转成字符串 new String(buf, 0, count);
            String s = baos.toString();
            System.out.println(s);

        }
    }

    static void read() {
        String s = "春花秋月何时了,往事知多少。小楼昨夜又东风,不堪回首月明中。";
        ByteArrayInputStream bais = null;
        OutputStream os = System.out;
        bais = new ByteArrayInputStream(s.getBytes());
        byte[] b = new byte[8];
        int len = 0;
        try {
            while ((len = bais.read(b)) != -1) {
                os.write(b, 0, len);
            }
            os.flush();
        } catch (Exception e) {

        } finally {
            try {
                bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        write();
        read();
    }
}
